"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Calculator, DollarSign, TrendingUp, PieChart, BarChart3, AlertCircle } from "lucide-react"

export default function FinancialCalculatorPage() {
  const router = useRouter()
  const [activeTab, setActiveTab] = useState("startup-cost")
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)

  // 启动成本计算器状态
  const [startupCost, setStartupCost] = useState({
    equipment: "",
    inventory: "",
    marketing: "",
    legal: "",
    rent: "",
    salaries: "",
    other: "",
  })

  // ROI计算器状态
  const [roiData, setRoiData] = useState({
    investment: "",
    revenue: "",
    costs: "",
    period: "12",
  })

  // 盈亏平衡点计算器状态
  const [breakEvenData, setBreakEvenData] = useState({
    fixedCosts: "",
    variableCostPerUnit: "",
    pricePerUnit: "",
  })

  // 现金流预测状态
  const [cashFlowData, setCashFlowData] = useState({
    initialCash: "",
    monthlyRevenue: "",
    monthlyCosts: "",
    months: "12",
  })

  // 计算启动成本
  const calculateStartupCost = () => {
    const total = Object.values(startupCost).reduce((sum, value) => {
      return sum + (Number.parseFloat(value) || 0)
    }, 0)
    return total
  }

  // 计算ROI
  const calculateROI = () => {
    const investment = Number.parseFloat(roiData.investment) || 0
    const revenue = Number.parseFloat(roiData.revenue) || 0
    const costs = Number.parseFloat(roiData.costs) || 0
    const profit = revenue - costs
    const roi = investment > 0 ? ((profit - investment) / investment) * 100 : 0
    return { profit, roi }
  }

  // 计算盈亏平衡点
  const calculateBreakEven = () => {
    const fixedCosts = Number.parseFloat(breakEvenData.fixedCosts) || 0
    const variableCost = Number.parseFloat(breakEvenData.variableCostPerUnit) || 0
    const price = Number.parseFloat(breakEvenData.pricePerUnit) || 0
    const contributionMargin = price - variableCost
    const breakEvenUnits = contributionMargin > 0 ? fixedCosts / contributionMargin : 0
    const breakEvenRevenue = breakEvenUnits * price
    return { breakEvenUnits, breakEvenRevenue, contributionMargin }
  }

  // 计算现金流预测
  const calculateCashFlow = () => {
    const initialCash = Number.parseFloat(cashFlowData.initialCash) || 0
    const monthlyRevenue = Number.parseFloat(cashFlowData.monthlyRevenue) || 0
    const monthlyCosts = Number.parseFloat(cashFlowData.monthlyCosts) || 0
    const months = Number.parseInt(cashFlowData.months) || 12
    const monthlyNetFlow = monthlyRevenue - monthlyCosts

    const projections = []
    let cumulativeCash = initialCash

    for (let i = 1; i <= months; i++) {
      cumulativeCash += monthlyNetFlow
      projections.push({
        month: i,
        revenue: monthlyRevenue,
        costs: monthlyCosts,
        netFlow: monthlyNetFlow,
        cumulativeCash,
      })
    }

    return projections
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  const startupTotal = calculateStartupCost()
  const roiResult = calculateROI()
  const breakEvenResult = calculateBreakEven()
  const cashFlowProjections = calculateCashFlow()

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" onClick={() => router.back()}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            <div className="flex items-center space-x-2">
              <Calculator className="w-6 h-6 text-blue-600" />
              <h1 className="text-xl font-semibold text-slate-900">财务计算器</h1>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="startup-cost">启动成本</TabsTrigger>
            <TabsTrigger value="roi">投资回报率</TabsTrigger>
            <TabsTrigger value="break-even">盈亏平衡</TabsTrigger>
            <TabsTrigger value="cash-flow">现金流预测</TabsTrigger>
          </TabsList>

          {/* 启动成本计算器 */}
          <TabsContent value="startup-cost" className="space-y-6 mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <DollarSign className="w-5 h-5" />
                    <span>启动成本输入</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="equipment">设备费用 (万元)</Label>
                    <Input
                      id="equipment"
                      type="number"
                      placeholder="0"
                      value={startupCost.equipment}
                      onChange={(e) => setStartupCost({ ...startupCost, equipment: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="inventory">库存/原材料 (万元)</Label>
                    <Input
                      id="inventory"
                      type="number"
                      placeholder="0"
                      value={startupCost.inventory}
                      onChange={(e) => setStartupCost({ ...startupCost, inventory: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="marketing">营销推广 (万元)</Label>
                    <Input
                      id="marketing"
                      type="number"
                      placeholder="0"
                      value={startupCost.marketing}
                      onChange={(e) => setStartupCost({ ...startupCost, marketing: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="legal">法务/注册 (万元)</Label>
                    <Input
                      id="legal"
                      type="number"
                      placeholder="0"
                      value={startupCost.legal}
                      onChange={(e) => setStartupCost({ ...startupCost, legal: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="rent">租金/装修 (万元)</Label>
                    <Input
                      id="rent"
                      type="number"
                      placeholder="0"
                      value={startupCost.rent}
                      onChange={(e) => setStartupCost({ ...startupCost, rent: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="salaries">员工薪资 (万元)</Label>
                    <Input
                      id="salaries"
                      type="number"
                      placeholder="0"
                      value={startupCost.salaries}
                      onChange={(e) => setStartupCost({ ...startupCost, salaries: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="other">其他费用 (万元)</Label>
                    <Input
                      id="other"
                      type="number"
                      placeholder="0"
                      value={startupCost.other}
                      onChange={(e) => setStartupCost({ ...startupCost, other: e.target.value })}
                    />
                  </div>
                </CardContent>
              </Card>

              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>计算结果</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-blue-600 mb-2">{startupTotal.toFixed(2)} 万元</div>
                      <p className="text-slate-600">预计启动成本</p>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>成本构成</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      {Object.entries(startupCost).map(([key, value]) => {
                        const amount = Number.parseFloat(value) || 0
                        const percentage = startupTotal > 0 ? (amount / startupTotal) * 100 : 0
                        const labels = {
                          equipment: "设备费用",
                          inventory: "库存/原材料",
                          marketing: "营销推广",
                          legal: "法务/注册",
                          rent: "租金/装修",
                          salaries: "员工薪资",
                          other: "其他费用",
                        }
                        return (
                          <div key={key} className="flex items-center justify-between">
                            <span className="text-sm text-slate-600">{labels[key]}</span>
                            <div className="flex items-center space-x-2">
                              <div className="w-20 bg-slate-200 rounded-full h-2">
                                <div className="bg-blue-600 h-2 rounded-full" style={{ width: `${percentage}%` }}></div>
                              </div>
                              <span className="text-sm font-medium w-12">{percentage.toFixed(1)}%</span>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </CardContent>
                </Card>

                <Card className="bg-yellow-50 border-yellow-200">
                  <CardContent className="p-4">
                    <div className="flex items-start space-x-2">
                      <AlertCircle className="w-5 h-5 text-yellow-600 mt-0.5" />
                      <div>
                        <h4 className="font-medium text-yellow-900">建议</h4>
                        <p className="text-sm text-yellow-800 mt-1">
                          建议准备额外20-30%的资金作为应急储备，以应对意外支出和市场变化。
                        </p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>

          {/* ROI计算器 */}
          <TabsContent value="roi" className="space-y-6 mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <TrendingUp className="w-5 h-5" />
                    <span>投资回报率计算</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="investment">初始投资 (万元)</Label>
                    <Input
                      id="investment"
                      type="number"
                      placeholder="0"
                      value={roiData.investment}
                      onChange={(e) => setRoiData({ ...roiData, investment: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="revenue">预期收入 (万元)</Label>
                    <Input
                      id="revenue"
                      type="number"
                      placeholder="0"
                      value={roiData.revenue}
                      onChange={(e) => setRoiData({ ...roiData, revenue: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="costs">运营成本 (万元)</Label>
                    <Input
                      id="costs"
                      type="number"
                      placeholder="0"
                      value={roiData.costs}
                      onChange={(e) => setRoiData({ ...roiData, costs: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="period">计算周期 (月)</Label>
                    <Input
                      id="period"
                      type="number"
                      placeholder="12"
                      value={roiData.period}
                      onChange={(e) => setRoiData({ ...roiData, period: e.target.value })}
                    />
                  </div>
                </CardContent>
              </Card>

              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>ROI 分析结果</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="text-center p-4 bg-blue-50 rounded-lg">
                        <div className="text-2xl font-bold text-blue-600 mb-1">{roiResult.roi.toFixed(2)}%</div>
                        <p className="text-sm text-blue-800">投资回报率</p>
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div className="text-center p-3 bg-green-50 rounded-lg">
                          <div className="text-lg font-semibold text-green-600">{roiResult.profit.toFixed(2)}万</div>
                          <p className="text-xs text-green-800">净利润</p>
                        </div>
                        <div className="text-center p-3 bg-slate-50 rounded-lg">
                          <div className="text-lg font-semibold text-slate-600">{roiData.period}个月</div>
                          <p className="text-xs text-slate-800">计算周期</p>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>ROI 评估</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      {roiResult.roi >= 20 && (
                        <Badge className="bg-green-100 text-green-700 w-full justify-center py-2">
                          优秀 - ROI超过20%，投资价值很高
                        </Badge>
                      )}
                      {roiResult.roi >= 10 && roiResult.roi < 20 && (
                        <Badge className="bg-blue-100 text-blue-700 w-full justify-center py-2">
                          良好 - ROI在10-20%之间，投资价值较高
                        </Badge>
                      )}
                      {roiResult.roi >= 0 && roiResult.roi < 10 && (
                        <Badge className="bg-yellow-100 text-yellow-700 w-full justify-center py-2">
                          一般 - ROI低于10%，需要优化
                        </Badge>
                      )}
                      {roiResult.roi < 0 && (
                        <Badge className="bg-red-100 text-red-700 w-full justify-center py-2">
                          亏损 - ROI为负，需要重新评估
                        </Badge>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>

          {/* 盈亏平衡点计算器 */}
          <TabsContent value="break-even" className="space-y-6 mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <BarChart3 className="w-5 h-5" />
                    <span>盈亏平衡点计算</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="fixedCosts">固定成本 (万元/月)</Label>
                    <Input
                      id="fixedCosts"
                      type="number"
                      placeholder="0"
                      value={breakEvenData.fixedCosts}
                      onChange={(e) => setBreakEvenData({ ...breakEvenData, fixedCosts: e.target.value })}
                    />
                    <p className="text-xs text-slate-500 mt-1">租金、工资、保险等固定支出</p>
                  </div>
                  <div>
                    <Label htmlFor="variableCostPerUnit">单位变动成本 (元)</Label>
                    <Input
                      id="variableCostPerUnit"
                      type="number"
                      placeholder="0"
                      value={breakEvenData.variableCostPerUnit}
                      onChange={(e) => setBreakEvenData({ ...breakEvenData, variableCostPerUnit: e.target.value })}
                    />
                    <p className="text-xs text-slate-500 mt-1">每件产品的材料、人工等成本</p>
                  </div>
                  <div>
                    <Label htmlFor="pricePerUnit">单位售价 (元)</Label>
                    <Input
                      id="pricePerUnit"
                      type="number"
                      placeholder="0"
                      value={breakEvenData.pricePerUnit}
                      onChange={(e) => setBreakEvenData({ ...breakEvenData, pricePerUnit: e.target.value })}
                    />
                    <p className="text-xs text-slate-500 mt-1">每件产品的销售价格</p>
                  </div>
                </CardContent>
              </Card>

              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>盈亏平衡分析</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="text-center p-4 bg-blue-50 rounded-lg">
                        <div className="text-2xl font-bold text-blue-600 mb-1">
                          {Math.round(breakEvenResult.breakEvenUnits)}
                        </div>
                        <p className="text-sm text-blue-800">盈亏平衡销量 (件/月)</p>
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div className="text-center p-3 bg-green-50 rounded-lg">
                          <div className="text-lg font-semibold text-green-600">
                            {breakEvenResult.breakEvenRevenue.toFixed(0)}
                          </div>
                          <p className="text-xs text-green-800">盈亏平衡收入 (元/月)</p>
                        </div>
                        <div className="text-center p-3 bg-purple-50 rounded-lg">
                          <div className="text-lg font-semibold text-purple-600">
                            {breakEvenResult.contributionMargin.toFixed(0)}
                          </div>
                          <p className="text-xs text-purple-800">单位贡献毛利 (元)</p>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card className="bg-blue-50 border-blue-200">
                  <CardContent className="p-4">
                    <h4 className="font-medium text-blue-900 mb-2">分析说明</h4>
                    <div className="space-y-1 text-sm text-blue-800">
                      <p>• 贡献毛利 = 售价 - 变动成本</p>
                      <p>• 盈亏平衡点 = 固定成本 ÷ 单位贡献毛利</p>
                      <p>• 超过盈亏平衡点的销量即可盈利</p>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </TabsContent>

          {/* 现金流预测 */}
          <TabsContent value="cash-flow" className="space-y-6 mt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <PieChart className="w-5 h-5" />
                    <span>现金流预测</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="initialCash">初始现金 (万元)</Label>
                    <Input
                      id="initialCash"
                      type="number"
                      placeholder="0"
                      value={cashFlowData.initialCash}
                      onChange={(e) => setCashFlowData({ ...cashFlowData, initialCash: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="monthlyRevenue">月收入 (万元)</Label>
                    <Input
                      id="monthlyRevenue"
                      type="number"
                      placeholder="0"
                      value={cashFlowData.monthlyRevenue}
                      onChange={(e) => setCashFlowData({ ...cashFlowData, monthlyRevenue: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="monthlyCosts">月支出 (万元)</Label>
                    <Input
                      id="monthlyCosts"
                      type="number"
                      placeholder="0"
                      value={cashFlowData.monthlyCosts}
                      onChange={(e) => setCashFlowData({ ...cashFlowData, monthlyCosts: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="months">预测月数</Label>
                    <Input
                      id="months"
                      type="number"
                      placeholder="12"
                      value={cashFlowData.months}
                      onChange={(e) => setCashFlowData({ ...cashFlowData, months: e.target.value })}
                    />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>现金流预测表</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="max-h-96 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="sticky top-0 bg-white">
                        <tr className="border-b">
                          <th className="text-left py-2">月份</th>
                          <th className="text-right py-2">收入</th>
                          <th className="text-right py-2">支出</th>
                          <th className="text-right py-2">净流量</th>
                          <th className="text-right py-2">累计现金</th>
                        </tr>
                      </thead>
                      <tbody>
                        {cashFlowProjections.map((projection) => (
                          <tr key={projection.month} className="border-b">
                            <td className="py-2">{projection.month}</td>
                            <td className="text-right py-2 text-green-600">+{projection.revenue.toFixed(1)}</td>
                            <td className="text-right py-2 text-red-600">-{projection.costs.toFixed(1)}</td>
                            <td
                              className={`text-right py-2 ${
                                projection.netFlow >= 0 ? "text-green-600" : "text-red-600"
                              }`}
                            >
                              {projection.netFlow >= 0 ? "+" : ""}
                              {projection.netFlow.toFixed(1)}
                            </td>
                            <td
                              className={`text-right py-2 font-medium ${
                                projection.cumulativeCash >= 0 ? "text-blue-600" : "text-red-600"
                              }`}
                            >
                              {projection.cumulativeCash.toFixed(1)}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 现金流警告 */}
            {cashFlowProjections.some((p) => p.cumulativeCash < 0) && (
              <Card className="bg-red-50 border-red-200">
                <CardContent className="p-4">
                  <div className="flex items-start space-x-2">
                    <AlertCircle className="w-5 h-5 text-red-600 mt-0.5" />
                    <div>
                      <h4 className="font-medium text-red-900">现金流警告</h4>
                      <p className="text-sm text-red-800 mt-1">预测显示某些月份可能出现现金流不足，建议：</p>
                      <ul className="text-sm text-red-800 mt-2 space-y-1">
                        <li>• 增加初始资金储备</li>
                        <li>• 优化收入和支出时间安排</li>
                        <li>• 考虑短期融资方案</li>
                      </ul>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </TabsContent>
        </Tabs>
      </main>
    </div>
  )
}
